# -*- encoding: utf-8 -*-

"""
@File:      file.py
@Time:      2023/05/22
@Author:    sunqingwei
@Version:   1.0
@Contact:   sunqingwei@uniontech.com
@License:   Mulan PSL v2
"""
import os
import logging

LOG = logging.getLogger('avocado.' + __name__)


class File():
    """
    Common def for file.
    """

    def branch(self):
        '''
        get branch of test machine
        '''
        try:
            with open('/etc/os-version', mode='r') as f:
                lines = f.readlines()
                for line in lines:
                    if line.find('EditionName') > -1:
                        return line.strip().split('=')[-1]
        except:
            return "System unsupported"

    def mkdir(self, *args):
        for path in args:
            if not os.path.exists(path):
                os.makedirs(path)

    def del_file(self, *args):
        '''
        delete file or dir
        '''
        for path in args:
            LOG.debug(f'delete path:{path}')
            if not os.path.exists(path):
                LOG.warning('path not exists')
                continue
            if os.path.isfile(path):
                os.remove(path)
            else:
                for i in os.listdir(path):
                    c_path = os.path.join(path, i)
                    if os.path.isdir(c_path):
                        self.del_file(c_path)
                    else:
                        os.unlink(c_path)
                os.rmdir(path)

    def read(self, path):
        '''
        read file
        :param path: file path
        :return: read data
        '''
        with open(path, mode='r', encoding='utf-8') as f:
            return f.read()

    def write(self, string, path, mode='a'):
        '''
        write string to file
        :param string: what want to write
        :param path: file path
        :param mode: wtite mode, defalt 'a', can chose 'w'
        :return: None
        '''
        with open(path, mode=mode, encoding='utf-8') as f:
            f.write(string)
